package com.itheima.health.security;


import com.alibaba.fastjson.JSON;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author ：wf
 * @date ：Created in 2022年06月08日
 * @description ：
 * @version: 1.0
 */
@Slf4j
@WebFilter(urlPatterns = "/*")
public class HealthSecurityFilter implements Filter {
    @Autowired
    private UserService userService;

    //匹配路径
    final AntPathMatcher pathMatcher= new AntPathMatcher();
    //授权的URL
    private String[]  authUrl = new String[]{
            "/user/login",
            "/user/logout",
            "/common/**",
            "/mobile/**"
    };
    //设置Url和对应的权限值
    private Map<String,String> urlWithPermission = new HashMap<>();

    private void initUrlWithPermission(){
        urlWithPermission.put("/checkitem/delete","CHECKITEM_DELETE");
        urlWithPermission.put("/checkitem/edit","CHECKITEM_EDIT");
        urlWithPermission.put("/checkitem/add","CHECKITEM_ADD");
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求路径
        String requestURI = request.getRequestURI();
        log.info("[拦截的请求路径]",requestURI);
        //判断路径是否需要登录
        boolean ischeckUrl = ischeckUrl(requestURI);
        if (ischeckUrl){
            //路径不需要拦截 进行放行
            chain.doFilter(request,response);
            return;
        }
        //判断用户是否进行了登录
        if (request.getSession().getAttribute("user")!=null){
            log.info("[登录了]"+request.getSession().getAttribute("user"));
            //获取存到session中的 用户信息
            User user = (User)request.getSession().getAttribute("user");
            //判断是否需要权限授权
            boolean ischeckquanxian = ischeckquanxian(requestURI, user);
            if (ischeckquanxian){
                //如果不需要授权 或者权限已授权 放行
                chain.doFilter(request,response);
                return;
            }else {
                log.info("[没有操作权限]");
                response.setContentType("application/json; charset=UTF-8");
                response.getWriter().write(JSON.toJSONString(new Result(false,"操作失败,没有操作权限")));
                return;
            }

        }else {
            log.info("[未登录]");
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(new Result(false,"未登录,请你进行登录")));

            return;
        }
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //权限列表
        initUrlWithPermission();
    }
    private boolean ischeckUrl(String reqUri){
        log.info("[请求路径:{}]"+reqUri);
        AntPathMatcher pathMatcher = new AntPathMatcher();
        for (String s : authUrl) {
            if (pathMatcher.match(s,reqUri)){
                log.info("[路径无需登录,放行]");
                return true;
            }
        }
        return false;
    }
    //判断当前路径是否有匹配的权限 如果有 需要验证用户是否拥有此权限 如果没有 证明不需要验证
    private boolean ischeckquanxian(String reqUrl, User user){
        AntPathMatcher pathMatcher = new AntPathMatcher();
        String keyUri = null;//定义一个空字符串
        for (String s : urlWithPermission.keySet()) {
            if (pathMatcher.match(s,reqUrl)){
                keyUri = s;//看看是否有匹配的
            }
        }
        if (keyUri == null){
            //如果没有匹配的内容 证明不需要验证
            log.info("[不需要验证权限]");
            return true;
        }
        //有匹配到的路径 需要权限
        //当前去请求的权限
        String urIqx = urlWithPermission.get(keyUri);
        //遍历用户的角色 是否有当前权限
        List<Permission> permissions = userService.findPermissionByUsername(user.getUsername());
        for (Permission permission : permissions) {
            if (pathMatcher.match(permission.getKeyword(),urIqx));
            return true;
        }
            log.info("[权限验证未通过]");
            return false;
    }

    @Override
    public void destroy() {

    }
}
